<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="../js/jquery-3.5.1.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<a id="a1" href="#">下载</a>
		<button id="btn" type="button">下载</button>
		<script type="text/javascript">
			$(document).ready(function() {
			   var jsonData = [
			    { id: '1001', name: 'dog', age: '10'},
			    { id: '1003', name: 'big', age: '12'},
			    { id: '1002', name: 'cat', age: '11'},{id: 1,name: '三国演义',tdate: '1899-08-09',price: '60.00',count: 1,account: "hh"},
				{id: 2,name: '水浒传',tdate: '1863-09-10',price: '69.00',count: 1,account: "haha"},
				{id: 3,name: '红楼梦',tdate: '1884-03-12',price: '99.00',count: 1,account: "aa"},
				{id: 4,name: '西游记',tdate: '1900-07-28',price: '9.00',count: 1,account: "aa"}
			    ];
			    jsonData.sort(function(a,b){
			    return a.age - b.age;
			    });
				$("#a1").click(function() {
					saveJSON(jsonData, 'jsonData.json');
				});
				$("#btn").click(function() {
					saveJSON(jsonData, 'jsonData.json');
				});
			})
			
			function saveJSON(data, filename) {
			    if (!data) {
			        alert('data is null');
			        return;
			    }
			    if (!filename) filename = 'json.json'
			    if (typeof data === 'object') {
			        data = JSON.stringify(data, undefined, 4)
			    }
			    var blob = new Blob([data], { type: 'text/json' });
			    var e = document.createEvent('MouseEvents');
			    var a = document.createElement('a');
			    a.download = filename;
			    a.href = window.URL.createObjectURL(blob);
			    a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
			    e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			    a.dispatchEvent(e);
			}
		</script>
	</body>
</html>
